﻿using System;
using System.Reactive.Linq;
using Caliburn.Micro;

namespace Scrabble.Model
{
    public class Stopwatch : PropertyChangedBase, IDisposable
    {
        private TimeSpan _totalRunningTime = TimeSpan.Zero;
        private DateTime _timeOfLastChange;
        private IDisposable _timer;

        public TimeSpan TotalRunningTime
        {
            get { return _totalRunningTime; }
            private set
            {
                if (_totalRunningTime == value) return;

                _totalRunningTime = value;
                _timeOfLastChange = DateTime.Now;

                NotifyOfPropertyChange(() => TotalRunningTime);
            }
        }

        public bool IsRunning
        {
            get { return _timer != null; }

            set
            {
                if (value == IsRunning) return;

                if (IsRunning)
                {
                    _timer.Dispose();
                    _timer = null;

                    UpdateTotalRunningTime();
                }
                else
                {
                    _timeOfLastChange = DateTime.Now;
                    _timer = Observable.Interval(TimeSpan.FromSeconds(1)).SubscribeOnDispatcher().Subscribe(x => UpdateTotalRunningTime());
                }
            }
        }

        public void Reset()
        {
            TotalRunningTime = TimeSpan.Zero;
        }

        private void UpdateTotalRunningTime()
        {
            TotalRunningTime += DateTime.Now - _timeOfLastChange;
        }

        void IDisposable.Dispose()
        {
            IsRunning = false;
        }
    }
}
